package com.tklab.smartcity.util;

import android.util.Log;
import android.widget.Toast;

import com.google.gson.Gson;
import com.tklab.smartcity.App;
import com.tklab.smartcity.service.IService;

import java.util.Map;

import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class RetrofitClient implements Callback<String> {
    IService service=null;
    BackJson backJson;

    public RetrofitClient(){
        service=RetrofitUtil.getInstance().create(IService.class);
    }

    public void get(String url,BackJson backJson){
        this.backJson=backJson;
        Call<String> call=service.get(url);
        call.enqueue(this);
    }

    /**
     * post请求方法,参数是json
     *
     * @param url      接口的方法
     * @param params   json的数据格式
     * @param backJson
     */
    public void post(String url, Map<String, Object> params, BackJson backJson) {
        this.backJson = backJson;
        Gson gson = new Gson();
        String json = gson.toJson(params);
        RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json;charset=UTF-8"), json);
        Call<String> call = service.post(url, body);
        call.enqueue(this);
    }

    /**
     * put请求方法,参数是json
     *
     * @param url
     * @param params
     * @param backJson
     */
    public void put(String url, Map<String, Object> params, BackJson backJson) {
        this.backJson = backJson;
        Gson gson = new Gson();
        String json = gson.toJson(params);
        RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json;charset=UTF-8"), json);
        Call<String> call = service.put(url, body);
        call.enqueue(this);
    }

    @Override
    public void onResponse(Call<String> call, Response<String> response) {
        String json=response.body();
        Log.d("TAG", "onResponse: "+json);
        backJson.success(json);
    }

    @Override
    public void onFailure(Call<String> call, Throwable throwable) {
        throwable.printStackTrace();
        call.cancel();
        Toast.makeText(App.context,"数据访问失败",Toast.LENGTH_LONG);

    }


    public interface BackJson{
        void success(String json);
    }
}
